package com.bringway.p2p.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bringway.p2p.dao.MenuCUDDao;
import com.bringway.p2p.dao.impl.MenuCUDDaoImpl;
import com.bringway.p2p.service.MenuCUDService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/*
 * 
 * @author fan
 * @className MenuCUDServiceImpl
 * @description 菜单增删改的业务逻辑接口实现类
 * @date 2015年12月14日下午6:52:11
 */
@Service
@Transactional
public class MenuCUDServiceImpl implements MenuCUDService {
	Logger logger=Logger.getLogger(MenuCUDDaoImpl.class);
	@Autowired
	private MenuCUDDao menuCUDDao;

	@Override
	public boolean addMenu(JSONObject parms) {

		return menuCUDDao.addMenu(parms) > 0;
	}

	@Override
	public boolean deleteMenu(JSONObject parms) {
		return menuCUDDao.deleteMenu(parms) > 0;
	}

	@Override
	public boolean updateMenu(JSONObject parms) {
		return menuCUDDao.updateMenu(parms) > 0;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.bringway.p2p.service.MenuCUDService#queryUser(net.sf.json.JSONObject)
	 */
	@Override
	public Map<String, Object> queryUser(JSONObject parms) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		Map<String, Object> parmsMap = new HashMap<String, Object>();
		String XM = parms.optString("XM");
		String GWMC = parms.optString("GWMC");
		String GYH = parms.optString("GYH");
		StringBuffer sql = new StringBuffer();
		// 首先查询用户角色关系表，根据roleid查询出userid;
		// 查询user--分页---子查询
		sql.append(
				" SELECT * FROM `d_ccb_fm`.`t_fm_sys_user` t where ID in(select USER_ID from `d_ccb_fm`.`t_fm_sys_user_role` t1 where t1.ROLE_ID = :ROLE_ID ) ");
		if (StringUtils.isNotEmpty(XM)) {
			sql.append(" and t.XM like :XM ");
			parmsMap.put("XM", "%"+XM+"%");
		}
		if (StringUtils.isNotEmpty(GWMC)) {
			sql.append(" and t.GWMC like :GWMC ");
			parmsMap.put("GWMC", "%"+GWMC+"%");
		}
		if (StringUtils.isNotEmpty(GYH)) {
			sql.append(" and t.GYH like :GYH ");
			parmsMap.put("GYH", "%"+GYH+"%");
		}
		sql.append(" limit :curpage,:pageSize ");
		parmsMap.put("ROLE_ID", parms.optString("ROLE_ID"));
		parmsMap.put("curpage", parms.optInt("curpage"));
		parmsMap.put("pageSize", parms.optInt("pageSize"));
		// 查询出用户集合;
		List list = menuCUDDao.query(sql.toString(), parmsMap);
		returnMap.put("userList", list);
		parmsMap.remove("curpage");
		parmsMap.remove("pageSize");
		// 查询出总页数;
		StringBuffer sql01 = new StringBuffer();
		sql01.append(
				" SELECT count(*) FROM `d_ccb_fm`.`t_fm_sys_user` t where ID in(select USER_ID from `d_ccb_fm`.`t_fm_sys_user_role` t1 where t1.ROLE_ID = :ROLE_ID ) ");
		if (StringUtils.isNotEmpty(XM)) {
			sql01.append(" and t.XM like :XM ");
		}
		if (StringUtils.isNotEmpty(GWMC)) {
			sql01.append(" and t.GWMC like :GWMC ");
		}
		if (StringUtils.isNotEmpty(GYH)) {
			sql01.append(" and t.GYH like :GYH ");
		}
		int total = menuCUDDao.getPageCount(sql01.toString(), parmsMap);
		returnMap.put("total", total);
		return returnMap;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.bringway.p2p.service.MenuCUDService#queryMenuIdsByUserId(net.sf.json.
	 * JSONObject)
	 */
	@Override
	public List<String> queryMenuIdsByUserId(JSONObject params) {
		Map<String, Object> map = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append(" select t.MENU_ID  from `d_ccb_fm`.`t_fm_sys_user_menu` t where t.USER_ID = :USER_ID ");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("USER_ID", params.optString("userId"));
		// 下面的list里面存放的是Map，所以需要遍历、
		List<Map<String, Object>> list = menuCUDDao.query(sql.toString(), paramMap);
		List<String> list2 = new ArrayList<String>();
		for (Map<String, Object> m : list) {
			String string = (String) m.get("MENU_ID");
			list2.add(string);
		}
		logger.info("queryMenuIdsByUserId sql is "+sql);
		return list2;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.bringway.p2p.service.MenuCUDService#saveMenuUserLink(net.sf.json.
	 * JSONObject)
	 */
	@Override
	public boolean saveMenuUserLink(JSONObject parms) {
		int isInsert = 0;
		JSONArray strings = parms.optJSONArray("menuIds");
		// 首先删除原先的关系
		String sql = " DELETE FROM `d_ccb_fm`.`t_fm_sys_user_menu` WHERE `USER_ID`= :USER_ID ";
		Map<String, String> parmsMap = new HashMap<String, String>();
		String USER_ID = parms.optString("userId");
		parmsMap.put("USER_ID", USER_ID);
		int i = menuCUDDao.updateMenuUser(sql, parmsMap);
		/* 删除成功了，那么就保存最新的 */
		int index = 0;
		for (int j = 0; j < strings.size(); j++) {
			parmsMap.clear();
			sql = " INSERT INTO `d_ccb_fm`.`t_fm_sys_user_menu` (`id`, `USER_ID`, `MENU_ID`) VALUES (:id, :USER_ID,:MENU_ID)";
			String id = UUID.randomUUID().toString();
			// String USER_ID = parms.optString("userId");
			String MENU_ID = strings.getString(j);
			parmsMap.put("id", id);
			parmsMap.put("USER_ID", USER_ID);
			parmsMap.put("MENU_ID", MENU_ID);
			isInsert = menuCUDDao.updateMenuUser(sql, parmsMap);
			if (isInsert > 0) {
				index++;
			}
		}
		return isInsert == strings.size();
	}

	@Override
	public List<Map<String, Object>> listMenuByParent(JSONObject params) {
		String sql = " select t1.ID,t1.NAME,t1.URL,t1.PARENT_ID,t1.PARAMS ,t1.ORDER_NUM,case when 1=1 then (select COUNT(*) from `d_ccb_fm`.`t_fm_sys_menu` t2 where t2.PARENT_ID=t1.ID) end CHILDCT from `d_ccb_fm`.`t_fm_sys_menu` t1 where PARENT_ID = :nodeId ORDER BY t1.ORDER_NUM DESC,id asc ";
		return menuCUDDao.query(sql, params);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.bringway.p2p.service.MenuCUDService#queryMenuRoleList(net.sf.json.
	 * JSONObject)
	 */
	@Override
	public List queryMenuRoleList(JSONObject params) {
		return menuCUDDao.queryMenuRoleList(params);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.bringway.p2p.service.MenuCUDService#MenuRoleRelatinShipSave(net.sf.
	 * json.JSONObject)
	 */
	@Override
	public boolean MenuRoleRelatinShipSave(JSONObject params) {
		int j = 0;
		String menuId = params.optString("menuId");
		String menuRoleIds = params.optString("menuRoleIds");
		String menuRoleNames = params.optString("menuRoleNames");
		String[] MenuRoleIds = menuRoleIds.split(",");
		String[] MenuRoleNames = menuRoleNames.split(",");
		// 保存之前，先删除原有的
		menuCUDDao.MenuRoleRelatinShipDel(params);

		for (int i = 0; i < MenuRoleIds.length; i++) {
			params.clear();
			params.put("MENU_ID", menuId);
			params.put("ROLE_ID", MenuRoleIds[i]);
			params.put("ROLE_NAME", MenuRoleNames[i]);
			int index = menuCUDDao.MenuRoleRelatinShipSave(params);
			if (index > 0) {
				j++;
			}
		}
		return j == MenuRoleIds.length;
	}

	@Override
	public List<Map<String, Object>> queryTreeMenuList(JSONObject params) {
		return menuCUDDao.queryTreeMenuList(params);
	}
}
